import { Modal, message, Form, Input, Button } from "antd";
import { useState } from "react";
import React from "react";
import { CloseOutlined } from "@ant-design/icons";
import ForgetPassword from "../forgetPassword/forgetPassword";
import { userApi } from "../../api/services/user/user";
import type { LoginRequest } from "../../api/dto/user";
import { useUser } from "../../hooks/useUser";

import "../../styles/globals.css";
import "./login.less";

interface LoginProps {
  open: boolean;
  onClose: () => void;
  onRegisterClick: () => void; 
  onLoginSuccess?: () => void;
}

const Login: React.FC<LoginProps> = ({ open, onClose, onRegisterClick, onLoginSuccess }) => {
  const [activeTab, setActiveTab] = useState<"account" | "qrcode">("account");
  const [activeMethod, setActiveMethod] = useState<"wechat" | "dingding">("wechat");
  const [showForgetPassword, setShowForgetPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const { login } = useUser();

  const resetToLogin = () => {
    setShowForgetPassword(false);
    setActiveTab("account");
  };

  // 处理登录
  const handleLogin = async (values: LoginRequest) => {
    try {
      setLoading(true);
      const response = await userApi.login(values);
      
      console.log('登录响应:', response);
      
      if (response.code === 0 || response.code === 200) {
        message.success("登录成功！");
        
        // 保存token
        if (response.data?.token) {
          localStorage.setItem("token", response.data.token);
          
          // 获取完整用户信息
          if (response.data.id) {
            try {
              const userInfoResponse = await userApi.getUserInfoById(response.data.id);
              
              if (userInfoResponse.code === 200 || userInfoResponse.code === 200) {
                const fullUserInfo = {
                  id: userInfoResponse.data?.id || response.data.id,
                  username: userInfoResponse.data?.username || response.data.username,
                  name: userInfoResponse.data?.name || response.data.name,
                  avatar: userInfoResponse.data?.avatar || response.data.avatar,
                  profileId: userInfoResponse.data?.profileId || response.data.profileId,
                  email: userInfoResponse.data?.email,
                  systemRole: userInfoResponse.data?.systemRole,
                  signature: userInfoResponse.data?.signature
                };
                
                localStorage.setItem("userInfo", JSON.stringify(fullUserInfo));
                console.log('完整用户信息:', fullUserInfo);
                // 更新全局用户状态
                login(fullUserInfo);
              } else {
                // 如果获取详细信息失败，使用登录返回的基本信息
                const basicUserInfo = {
                  id: response.data.id,
                  username: response.data.username,
                  name: response.data.name,
                  avatar: response.data.avatar,
                  profileId: response.data.profileId
                };
                localStorage.setItem("userInfo", JSON.stringify(basicUserInfo));
                login(basicUserInfo);
              }
            } catch (error) {
              console.error("获取用户详细信息失败:", error);
              // 使用登录返回的基本信息
              const basicUserInfo = {
                id: response.data.id,
                username: response.data.username,
                name: response.data.name,
                avatar: response.data.avatar,
                profileId: response.data.profileId
              };
              localStorage.setItem("userInfo", JSON.stringify(basicUserInfo));
              login(basicUserInfo);
            }
          }
          
          // 关闭登录窗口
          onClose();
          
          // 触发登录成功回调
          if (onLoginSuccess) {
            onLoginSuccess();
          }
        }
      } else {
        message.error(response.message || response.msg || "登录失败，请检查账号和密码");
      }
    } catch (error) {
      console.error("登录出错:", error);
      message.error("登录失败，请稍后再试");
    } finally {
      setLoading(false);
    }
  };

  if (!open) {
    return null;
  }
  return (
    <Modal
      open={open}
      onCancel={() => {
        onClose();
        resetToLogin(); // 关闭时重置状态
      }}
      closable={false}
      footer={null}
      width={400}
      style={{ top: activeTab === "qrcode" ? 0 : 50 }} // 扫码登录时更靠上
      classNames={{
        content: "bg-transparent",
      }}
      className="login-modal"
    >
      {showForgetPassword ? (
        <ForgetPassword onBack={resetToLogin} />
      ) : (
        <div className="login-container">
          <button
            onClick={onClose}
            className="close-button"
          >
            <CloseOutlined />
          </button>
          
          <div className="login-header">
            <img
              src="https://makabaka7-x.github.io/Swust_UI_New/images/logo.png"
              alt="SwustOJ Logo"
              className="login-logo"
            />
            <h2 className="login-title">登录 SwustOJ</h2>
          </div>

          {/* nav */}
          <div className="login-tabs">
            <div className="login-tab">
              <span
                onClick={() => setActiveTab("account")}
                className={`login-tab-item ${activeTab === "account" ? "active" : ""}`}
              >
                账号密码登录
              </span>
            </div>
            <div className="login-tab">
              <span
                onClick={() => setActiveTab("qrcode")}
                className={`login-tab-item ${activeTab === "qrcode" ? "active" : ""}`}
              >
                扫码登录
              </span>
            </div>
          </div>

          {/* Content */}
          {activeTab === "account" ? (
            <div className="login-form-container">
              <Form form={form} onFinish={handleLogin} layout="vertical">
                <Form.Item
                  name="identifier"
                  rules={[{ required: true, message: "请输入学号或邮箱" }]}
                >
                  <Input placeholder="学号/邮箱" className="login-input" />
                </Form.Item>
                <Form.Item
                  name="password"
                  rules={[{ required: true, message: "请输入密码" }]}
                >
                  <Input.Password placeholder="密码" className="login-input" />
                </Form.Item>
                <Form.Item>
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="login-button"
                    loading={loading}
                >
                  登录
                  </Button>
                </Form.Item>
              </Form>
              <div className="login-actions">
                <button
                  onClick={() => setShowForgetPassword(true)}
                  className="login-action-button"
                >
                  忘记密码？
                </button>
                <button
                  onClick={() => {
                    onClose(); // 关闭登录弹窗
                    onRegisterClick(); // 触发注册弹窗
                  }}
                  className="login-action-button"
                >
                  注册账号
                </button>
              </div>
            </div>
          ) : (
            <div className="qrcode-container">
              <div className="qrcode-content">
                <div className="qrcode-wrapper">
                    <img
                      src={
                        activeMethod === "wechat"
                          ? "/images/wechat-qr.png"
                          : "/images/dingding-qr.png"
                      }
                      alt={
                        activeMethod === "wechat"
                          ? "微信登录二维码"
                          : "钉钉登录二维码"
                      }
                    className="qrcode-image"
                    />
                  </div>
                <p className="qrcode-tip">
                    {activeMethod === "wechat"
                      ? "请使用微信扫描二维码登录"
                      : activeMethod === "dingding"
                      ? "请使用钉钉扫描二维码登录"
                      : "请扫描二维码登录"}
                  </p>
                </div>
              <div className="qrcode-separator">其它登录方式</div>
              <div className="qrcode-methods">
                  <div
                  className={`qrcode-method-button ${activeMethod === "wechat" ? "active" : ""}`}
                    onClick={() => setActiveMethod("wechat")}
                  >
                    <img
                      src="https://makabaka7-x.github.io/Swust_UI_New/images/%E5%BE%AE%E4%BF%A1.png"
                    className="qrcode-method-icon"
                    alt="微信"
                  />
                  </div>
                  <div
                  className={`qrcode-method-button ${activeMethod === "dingding" ? "active" : ""}`}
                    onClick={() => setActiveMethod("dingding")}
                  >
                    <img
                      src="https://makabaka7-x.github.io/Swust_UI_New/images/%E9%92%89%E9%92%8901.png"
                    className="qrcode-method-icon"
                    alt="钉钉"
                  />
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </Modal>
  );
};

export default Login;

